<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Han">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/try6.gitee.io/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/try6.gitee.io/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/try6.gitee.io/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/try6.gitee.io/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/try6.gitee.io/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/try6.gitee.io/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/try6.gitee.io/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="同源啊跨域啊好像也要被讲烂了，网上随便搜搜也有很多详细的教程，阮老师的文章也是其中的经典。 前段时间经历了第一次前端面试，笔试开头的基础题就是问同源策略，当时菜逼如我答的不好，虽然最后结果是好的，但是还是想做一个整理给自己一雪前耻 浏览器的同源策略首先当然要介绍一下浏览器的同源策略  端口相同 域名相同 协议相同  这是用于保护用户数据的安全，防止恶意访问 按照阮老师的说法，目前，如果非同源，共有">
<meta property="og:type" content="article">
<meta property="og:title" content="同源策略与跨域">
<meta property="og:url" content="http://try66.gitee.io/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/index.html">
<meta property="og:site_name" content="Hello JS">
<meta property="og:description" content="同源啊跨域啊好像也要被讲烂了，网上随便搜搜也有很多详细的教程，阮老师的文章也是其中的经典。 前段时间经历了第一次前端面试，笔试开头的基础题就是问同源策略，当时菜逼如我答的不好，虽然最后结果是好的，但是还是想做一个整理给自己一雪前耻 浏览器的同源策略首先当然要介绍一下浏览器的同源策略  端口相同 域名相同 协议相同  这是用于保护用户数据的安全，防止恶意访问 按照阮老师的说法，目前，如果非同源，共有">
<meta property="og:locale" content="zh-Han">
<meta property="og:updated_time" content="2018-08-16T13:16:35.019Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="同源策略与跨域">
<meta name="twitter:description" content="同源啊跨域啊好像也要被讲烂了，网上随便搜搜也有很多详细的教程，阮老师的文章也是其中的经典。 前段时间经历了第一次前端面试，笔试开头的基础题就是问同源策略，当时菜逼如我答的不好，虽然最后结果是好的，但是还是想做一个整理给自己一雪前耻 浏览器的同源策略首先当然要介绍一下浏览器的同源策略  端口相同 域名相同 协议相同  这是用于保护用户数据的安全，防止恶意访问 按照阮老师的说法，目前，如果非同源，共有">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/try6.gitee.io/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://try66.gitee.io/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/"/>





  <title>同源策略与跨域 | Hello JS</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cc7e3057efb482b0f56c29d2716384da";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Han">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/try6.gitee.io/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hello JS</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">所有的安排都是最好的</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/try6.gitee.io/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/try6.gitee.io/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://try66.gitee.io/try6.gitee.io/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Try_Luies">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/try6.gitee.io/images/pic.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hello JS">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">同源策略与跨域</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-02-07T06:47:46+08:00">
                2018-02-07
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2018/02/07/2018-02-07同源策略与跨域/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/" class="leancloud_visitors" data-flag-title="同源策略与跨域">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">Visitors&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>同源啊跨域啊好像也要被讲烂了，网上随便搜搜也有很多详细的教程，阮老师的文章也是其中的经典。</p>
<p>前段时间经历了第一次前端面试，笔试开头的基础题就是问同源策略，当时菜逼如我答的不好，虽然最后结果是好的，但是还是想做一个整理给自己一雪前耻</p>
<h3 id="浏览器的同源策略"><a href="#浏览器的同源策略" class="headerlink" title="浏览器的同源策略"></a>浏览器的同源策略</h3><p>首先当然要介绍一下浏览器的同源策略</p>
<ul>
<li>端口相同</li>
<li>域名相同</li>
<li>协议相同</li>
</ul>
<p>这是用于保护用户数据的安全，防止恶意访问</p>
<p>按照阮老师的说法，目前，如果非同源，共有三种行为受到限制。</p>
<ol>
<li>Cookie、LocalStorage 和 IndexDB 无法读取。</li>
<li>Dom无法获取</li>
<li>Ajax请求<br>如何实现跨域，在有些必要的场合突破这些限制呢<a id="more"></a>
<h3 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h3></li>
</ol>
<h4 id="window-domain设置同一父域名"><a href="#window-domain设置同一父域名" class="headerlink" title="window.domain设置同一父域名"></a>window.domain设置同一父域名</h4><p>对于同一个页面，不同的iframe之间是可以共享window对象，只不过不能使用另一个页面window的对象的属性和方法（极少部分除外，如h5中的postMessage方法）。此时，可以使用domain将iframe设置为相同的域。</p>
<p>如有一个网页A<code>http://w1.example.a.com</code>，一个网页B<code>http://w2,example.b.com</code>。<br>只要设置相同的<code>document.domain</code>，两个页面就能共享数据和DOM（<code>LocalStorage</code> 和 <code>IndexDB</code> 无法通过这种方法传递）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">document.domain = &quot;example.com&quot; //必须为自身 或父域</span><br></pre></td></tr></table></figure></p>
<p>这两个网页就能互相访问dom和数据了。</p>
<p>比如你在网页A设置一个cookie<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//网页A</span><br><span class="line">document.cookie =&quot;i&apos;m A&quot;</span><br></pre></td></tr></table></figure></p>
<p>就可以在网页B访问到这个属性<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//网页B</span><br><span class="line">document.cookie // i&apos;m A</span><br></pre></td></tr></table></figure></p>
<h3 id="DOM的获取"><a href="#DOM的获取" class="headerlink" title="DOM的获取"></a>DOM的获取</h3><p>如果两个窗口一级域名相同，只是二级域名不同，那么设置上一节介绍的<code>document.domain</code>属性，就可以规避同源政策，拿到DOM。</p>
<p>对于完全不同源的网站,可以采用下面三种方法</p>
<ul>
<li><code>window.name</code></li>
<li>跨文档通信API（Cross-document messaging）</li>
<li>片段识别符（fragment identifier）<h5 id="window-name"><a href="#window-name" class="headerlink" title="window.name"></a>window.name</h5><code>window.name</code>这个浏览器窗口属性最大的特点就是，只要在同一个窗口中，无论是否同源，所有页面都能共享这个属性。每个页面对window.name都有读写的权限</li>
</ul>
<p>而且<code>window.name</code>可以存储容量比较大，一般有2M（不同浏览器容量不容）</p>
<h5 id="跨文档通信API"><a href="#跨文档通信API" class="headerlink" title="跨文档通信API"></a>跨文档通信API</h5><p>H5为了解决跨源的问题，引入了一个全新的API,为window新增了一个方法<code>window.postMessage</code>，允许跨窗口通信，无论是否同源。</p>
<p>比如在窗口<a href="http://aaa.com中，想要向另一个页面http://bbb.com发送消息。调用postMessage方法即可" target="_blank" rel="noopener">http://aaa.com中，想要向另一个页面http://bbb.com发送消息。调用postMessage方法即可</a><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//aaa.com中写入</span><br><span class="line">var popup = window.open(&apos;http://bbb.com&apos;, &apos;title&apos;);</span><br><span class="line">popup.postMessage(&apos;Hello World!&apos;, &apos;http://bbb.com&apos;);</span><br></pre></td></tr></table></figure></p>
<p>bbb中通过message事件监听消息<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">window.addEventListener(&apos;message&apos;, function(e) &#123;</span><br><span class="line">  console.log(e.data);</span><br><span class="line">&#125;,false);</span><br></pre></td></tr></table></figure></p>
<p>其中message事件对象event提供三个属性</p>
<ul>
<li>event.source：消息来源的地址</li>
<li>event.origin：消息发向的地址</li>
<li>event.data：消息内容</li>
</ul>
<h5 id="片段识别符"><a href="#片段识别符" class="headerlink" title="片段识别符"></a>片段识别符</h5><p>片段识别符指的是，URL的#号后面的部分。如果仅是识别符改变，不会导致页面刷新。父页面可以将信息写入子页面的识别符中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">var src = originURL + &apos;#&apos; + data;</span><br><span class="line">document.getElementById(&apos;myIFrame&apos;).src = src;</span><br></pre></td></tr></table></figure></p>
<p>子页面通过<code>onhashchange</code>监听<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">window.onhashchange = checkMessage;</span><br><span class="line"></span><br><span class="line">function checkMessage() &#123;</span><br><span class="line">  var message = window.location.hash;</span><br><span class="line">  // ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>子页面也可以把信息写入父页面的识别符<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">parent.location.href= target + &quot;#&quot; + hash;</span><br></pre></td></tr></table></figure></p>
<h3 id="AJAX请求的跨域"><a href="#AJAX请求的跨域" class="headerlink" title="AJAX请求的跨域"></a>AJAX请求的跨域</h3><p>针对AJAX请求，有两种跨域方式</p>
<ol>
<li>JSONP 只支持get请求，不支持post请求；兼容性较好</li>
<li>CORS 支持所有请求；不兼容老旧浏览器<h5 id="jsonp跨域"><a href="#jsonp跨域" class="headerlink" title="jsonp跨域"></a>jsonp跨域</h5>jsonp是利用script标签可以跨域访问资源的特性，在页面内动态插入一个script标签，向服务器发起数据的跨域请求。服务器收到请求后，将数据放在一个指定名字的回调函数中传回<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">function addScriptTag(src) &#123;</span><br><span class="line">  var script = document.createElement(&apos;script&apos;);</span><br><span class="line">  script.setAttribute(&quot;type&quot;,&quot;text/javascript&quot;);</span><br><span class="line">  script.src = src;</span><br><span class="line">  document.body.appendChild(script);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">window.onload = function () &#123;</span><br><span class="line">  addScriptTag(&apos;http://example.com/ip?callback=foo&apos;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function foo(data) &#123;</span><br><span class="line">  console.log(&apos;Your public IP address is: &apos; + data.ip);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h5 id="cors跨域"><a href="#cors跨域" class="headerlink" title="cors跨域"></a>cors跨域</h5><p>cors请求的局限就小很多了，它是一个W3C标准，允许向跨源服务器，发起<a href="http://www.ruanyifeng.com/blog/2012/09/xmlhttprequest_level_2.html" target="_blank" rel="noopener"><code>XMLHttpRequest</code></a>请求。支持IE10及其以上。</p>
<p>整个CORS通信过程，都是浏览器自动完成，不需要用户参与。</p>
<p>对于开发者来说，CORS通信与同源的AJAX通信没有差别，代码完全一样。浏览器一旦发现AJAX请求跨源，就会自动添加一些附加的头信息，有时还会多出一次附加的请求，但用户不会有感觉。</p>
<p>因此，实现CORS通信的关键是服务器。只要服务器实现了CORS接口，就可以跨源通信。</p>
<p>cors请求具体实现方式可以参考阮老师的文章<a href="http://www.ruanyifeng.com/blog/2016/04/cors.html" target="_blank" rel="noopener">跨域资源共享 CORS 详解——阮一峰</a></p>
<p>参考资料：<br><a href="http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html" target="_blank" rel="noopener">浏览器同源策略及其避规方法——阮一峰</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>Donate</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Try_Luies WeChat Pay"/>
        <p>WeChat Pay</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Try_Luies Alipay"/>
        <p>Alipay</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/try6.gitee.io/2018/02/07/2018-02-07浏览器版本的判断思路/" rel="next" title="浏览器版本的判断思路">
                <i class="fa fa-chevron-left"></i> 浏览器版本的判断思路
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/try6.gitee.io/2018/02/08/2018-02-08电子地图需求文档/" rel="prev" title="电子地图需求文档">
                电子地图需求文档 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/try6.gitee.io/images/pic.jpg"
                alt="Try_Luies" />
            
              <p class="site-author-name" itemprop="name">Try_Luies</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/try6.gitee.io/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/try6" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-GitHub"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/7a6944daafc3" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-globe"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="www.baidu.com" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-微博"></i>微博</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#浏览器的同源策略"><span class="nav-number">1.</span> <span class="nav-text">浏览器的同源策略</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cookie"><span class="nav-number">2.</span> <span class="nav-text">cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#window-domain设置同一父域名"><span class="nav-number">2.1.</span> <span class="nav-text">window.domain设置同一父域名</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DOM的获取"><span class="nav-number">3.</span> <span class="nav-text">DOM的获取</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#window-name"><span class="nav-number">3.0.1.</span> <span class="nav-text">window.name</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#跨文档通信API"><span class="nav-number">3.0.2.</span> <span class="nav-text">跨文档通信API</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#片段识别符"><span class="nav-number">3.0.3.</span> <span class="nav-text">片段识别符</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AJAX请求的跨域"><span class="nav-number">4.</span> <span class="nav-text">AJAX请求的跨域</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#jsonp跨域"><span class="nav-number">4.0.1.</span> <span class="nav-text">jsonp跨域</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#cors跨域"><span class="nav-number">4.0.2.</span> <span class="nav-text">cors跨域</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Try_Luies</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/try6.gitee.io/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/try6.gitee.io/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/try6.gitee.io/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/try6.gitee.io/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/try6.gitee.io/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/try6.gitee.io/js/src/bootstrap.js?v=5.1.4"></script>



  


  

    
      <script id="dsq-count-scr" src="https://try.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://try66.gitee.io/try6.gitee.io/2018/02/07/2018-02-07同源策略与跨域/';
          this.page.identifier = '2018/02/07/2018-02-07同源策略与跨域/';
          this.page.title = '同源策略与跨域';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://try.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
